/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controls;

import java.io.IOException;
import java.io.Serializable;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import others.Console;
import others.Login;
import others.User;
import servlets.BackupsXML;
import table.Application;
import table.Site;

/**
 *
 * @author Agata
 */
@ManagedBean
@SessionScoped
public class ApplicationsControl implements Serializable {

    private String path;
    private String name;
    private String appPool;
    private String site;
    private String bindings;
    private String physicalPath;
    private List<Application> list = null;
    private Application selectedElement = null;
    @ManagedProperty(value = "#{login}")
    private Login login;

    /** Creates a new instance of SitesAdd */
    public ApplicationsControl() {
        list = new ArrayList<Application>();
        doList();
    }

    public void delete(ActionEvent actionEvent) {
        if (login.userPermited(User.PERM_ADMIN)) {
            String query = "c:\\Windows\\System32\\inetsrv\\appcmd delete app "
                    + "\"" + selectedElement.getName();
            String log = Console.request(query);
            FacesMessage msg = null;
            Pattern p = Pattern.compile("deleted");
            Matcher m = p.matcher(log);
            if (m.find()) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Hura!",
                        "Usunięto aplikację: " + name);
                list.remove(selectedElement);
            } else {
                msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Ojej!",
                        "Nieusunięto aplikacji: " + name + ". Sprawdź dane.");
            }

            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
    }

    public void modify(ActionEvent actionEvent) {
        if (login.userPermited(User.PERM_ADMIN)) {
            String query = "c:\\Windows\\System32\\inetsrv\\appcmd set app "
                    + "\"" + selectedElement.getName() + "\" /applicationPool:\"" + appPool + "\"";
            System.out.print(query);
            String log = Console.request(query);
            FacesMessage msg = null;
            Pattern p = Pattern.compile("changed");
            Matcher m = p.matcher(log);
            if (m.find()) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Hura!",
                        "Zmodyfikowano aplikację: " + selectedElement.getName());
                selectedElement.setBindings(bindings);
            } else {
                msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Ojej!",
                        "Niezmodyfikowano aplikacji: " + name + ". Sprawdź dane.");
            }

            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
    }

    public void add(ActionEvent actionEvent) {
        if (login.userPermited(User.PERM_ADMIN)) {
            String query = "c:\\Windows\\System32\\inetsrv\\appcmd add app /site.name:\""
                    + name + "\" /path:\"" + path + "\" /physicalPath:\"" + physicalPath + "\" ";
            String log = Console.request(query);
            FacesMessage msg = null;
            Pattern addedp = Pattern.compile("added");
            Matcher addedm = addedp.matcher(log);
            Pattern dupp = Pattern.compile("duplicate");
            Matcher dupm = dupp.matcher(log);
            if (addedm.find()) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Hura!",
                        "Dodano aplikację: " + name);
                list.add(new Application(name, path, physicalPath));
            } else if (dupm.find()) {
                msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Błąd!",
                        "Dodawana aplikacja już istnieje - nazwa i id muszą być unikatowe!");
            } else {
                msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Błąd!",
                        "Spróbuj ponownie. Sprawdź poprawność danych!");
            }

            FacesContext.getCurrentInstance().addMessage(null, msg);
            name = path = physicalPath = null;
        }
    }

    private void doList() {
        String resp = Console.request("c:\\Windows\\System32\\inetsrv\\appcmd list app /xml");
        System.out.print(resp);
        // creating javaDom parser
        DocumentBuilderFactory builderFactory =
                DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
            builder = builderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(BackupsXML.class.getName()).log(Level.SEVERE, null, ex);
        }
        Document document = null;
        try {
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(resp));
            document = builder.parse(is);
        } catch (IOException ex) {
            Logger.getLogger(BackupControl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(BackupsXML.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (document != null) {
            Element rootElement = document.getDocumentElement();
            NodeList nodes = rootElement.getChildNodes();

            for (int i = 0; i < nodes.getLength(); i++) {
                Node node = nodes.item(i);
                if (node instanceof Element) {
                    //a child element to process
                    Element child = (Element) node;
                    list.add(new Application(child.getAttribute("APP.NAME"),
                            child.getAttribute("path"), child.getAttribute("APPPOOL.NAME"),
                            child.getAttribute("SITE.NAME")));
                    System.out.print(list.get(list.size() - 1).toString());
                }
            }
        }
    }

    public String getAppPool() {
        return appPool;
    }

    public void setAppPool(String appPool) {
        this.appPool = appPool;
    }

    public List<Application> getList() {
        return list;
    }

    public void setList(List<Application> list) {
        this.list = list;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public Application getSelectedElement() {
        return selectedElement;
    }

    public void setSelectedElement(Application selectedElement) {
        this.selectedElement = selectedElement;
    }

    public String getSite() {
        return site;
    }

    public void setSite(String site) {
        this.site = site;
    }

    public String getBindings() {
        return bindings;
    }

    public void setBindings(String bindings) {
        this.bindings = bindings;
    }

    public String getPhysicalPath() {
        return physicalPath;
    }

    public void setPhysicalPath(String physicalPath) {
        this.physicalPath = physicalPath;
    }

    public Login getLogin() {
        return login;
    }

    public void setLogin(Login login) {
        this.login = login;
    }
}
